<template>
  <div>
    <div style="
                background: #fff;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                color: #666;
                padding:20px
            ">
      <div style="width: 100%">
        <span style="
                        font-size: 20px;
                        margin: 30px 40px;
                        display: inline-block;
                        color: #000;
                    ">
          <i class="el-icon-document"></i>
          活动基本信息
        </span>
        <el-button size="mini" @click="goback()" type="primary"
          style="margin-left: 1000px; margin-bottom: 20px">返回</el-button>
        <el-form :disabled="$route.params.flag3" :model="ruleForm" :rules="rules" ref="ruleForm"
          label-width="150px" class="demo-ruleForm">


          <div class="grid-content bg-purple">
            <el-form-item label="活动名称" prop="activityName">
              <el-input v-model="ruleForm.activityName" type="textarea" maxlength="30" style="width:300px" :rows="3"
                show-word-limit></el-input>
            </el-form-item>
          </div>


          <div class="grid-content bg-purple;position:relative">
            <el-form-item label="活动有效期" required>
              <el-col :span="10">
                <el-form-item prop="date1">
                  <el-date-picker placeholder="开始日期" v-model="ruleForm.date1" type="datetime" style="width: 300px"
                    format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                </el-form-item>
              </el-col>


              <el-col class="line" :span="2" style="    position: absolute;

    left: 310px;">至</el-col>
              <el-col :span="10" style="    position: absolute;

    left: 340px;">
                <el-form-item prop="date2">
                  <el-date-picker placeholder="结束日期" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss" v-model="ruleForm.date2" style="width: 300px"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-form-item>
          </div>



          <div class="grid-content bg-purple">
            <el-form-item label="兑奖截至日期" required>
              <el-col :span="10">
                <el-form-item prop="cashDeadline">
                  <el-date-picker placeholder="选择日期" v-model="ruleForm.cashDeadline" type="datetime"
                    style="width: 300px" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" @change="
                      (data) => {
                        ruleForm.cashDeadline = todataformat(
                          data
                        );
                      }
                    "></el-date-picker>
                </el-form-item>
              </el-col>
            </el-form-item>
          </div>


          <div class="grid-content bg-purple">
            <el-form-item label="活动规则" prop="activityRule">
              <el-input type="textarea" v-model="ruleForm.activityRule" style="width:500px" :rows="6"></el-input>
            </el-form-item>
          </div>

          <!-- <el-form-item label="活动背景图:" prop="imgListone"> -->
          <!-- <image-upload v-model="ruleForm.imgListone" :size="'400x400'" :limit="1"></image-upload> -->
          <el-form-item label="活动背景图片:" prop="activityImg">
            <single-image-upload v-model="ruleForm.activityImg" :imageWidth="150" :imageHeight="150" :width="'150px'"
              :height="'150px'"></single-image-upload>
            <!-- <div class="demo-image__preview" v-if="!this.$route.params.flag3">
                    <el-image style="width: 120px; height: 120px" :src="ruleForm.activityImg"></el-image>
                </div> -->
          </el-form-item>
          <!-- </el-form-item> -->

          <el-form-item label="专卖店活动入口:" prop="activityEntranceImg">
            <single-image-upload v-model="ruleForm.activityEntranceImg" :imageWidth="150" :imageHeight="150" :width="'150px'"
              :height="'150px'"></single-image-upload>
          </el-form-item>


          <!-- <el-form-item label="获得抽奖资格金额" prop="activityScore">
            <el-input v-model.number="ruleForm.activityScore" type="number" style="width:200px" min="0"
              class="input_edit">
              <template slot="append">元</template>
            </el-input>
            <span>（单笔订单金额）</span>
          </el-form-item> -->

          <el-form-item label="免费抽奖次数" prop="activityLimit">
            <el-input v-model.number="ruleForm.activityLimit" type="number" min="0" style="width:200px"
              class="input_edit">
              <template slot="append">次</template>
            </el-input>
          </el-form-item>

          <el-form-item label="每次消耗积分" prop="score">
            <el-input v-model.number="ruleForm.score" type="number" min="0" style="width:200px"
              class="input_edit">
            </el-input>
          </el-form-item>

          <el-form-item label="专项积分名称" prop="scoreName">
            <el-input v-model="ruleForm.scoreName" style="width:200px"
              class="input_edit">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div style="
                background: #fff;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                color: #666;
            ">
      <div style="width: 100%">
        <span style="
                        font-size: 20px;
                        margin: 30px 40px;
                        display: inline-block;
                        color: #000;
                    ">
          <i class="el-icon-document"></i>
          赠品配置
        </span>

        <el-table :data="tableData" style="width: 100%" border :header-cell-style="{
          background: '#eef1f6',
          color: '#606266',
        }">
          <el-table-column type="index" label="序号" align="center" width="60" fixed="left"></el-table-column>

          <el-table-column prop="prizeLevelName" label="赠品等级名称" width="130">
            <template slot-scope="scope">
              <el-input v-model="scope.row.prizeLevelName" :disabled="flag3"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="giftCode" label="赠品编码"></el-table-column>
          <el-table-column prop="giftName" label="赠品名称"></el-table-column>
          <el-table-column prop="giftPic" label="赠品图片">
            <template slot-scope="scope">
              <img :src="scope.row.giftPic" v-if="
                scope.row.giftPic != '' &&
                scope.row.giftPic != null
              " width="70" height="50" />
            </template>
          </el-table-column>
          <el-table-column prop="giftDesc" label="赠品描述" show-overflow-tooltip></el-table-column>
          <el-table-column prop="giftType" label="赠品类型">
            <template slot-scope="scope">
              <span v-if="scope.row.giftType === 1">实物赠品</span>
              <span v-if="scope.row.giftType === 2">虚拟赠品</span>
            </template>
          </el-table-column>
          <el-table-column prop="deliveryType" label="配送方式" width="240" align="center">
            <template slot-scope="scope">
              <el-radio-group v-model="scope.row.deliveryType" v-if="scope.row.giftType === 1" :disabled="flag3"
                size="mini">
                <el-radio-button label="1">专卖店配送</el-radio-button>
                <el-radio-button label="2">五粮液总部配送</el-radio-button>
              </el-radio-group>
              <span v-if="scope.row.giftType === 2">——————</span>
            </template>
          </el-table-column>
          <!-- <el-table-column
                        prop="validType"
                        label="有效期类型"
                        width="180"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <el-radio-group
                                v-model="scope.row.validType"
                                v-if="
                                    scope.row.giftType === 2 &&
                                    scope.row.giftStyle !== 3 &&
                                    scope.row.giftStyle !== 5
                                "
                                :disabled="flag3"
                            >
                                <el-radio-button label="1"
                                    >天数</el-radio-button
                                >
                                <el-radio-button label="2"
                                    >日期</el-radio-button
                                >
                            </el-radio-group>
                            <span v-else>——————</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="giftStyle"
                        label="类型"
                        v-if="false"
                    ></el-table-column>
                    <el-table-column
                        prop="validDate"
                        label="有效天数"
                        align="center"
                        width="150"
                    >
                        <template slot-scope="scope">
                            <el-input
                                v-model="scope.row.validDate"
                                @blur="numberBlur($event, '有效天数')"
                                v-if="
                                    scope.row.giftType === 2 &&
                                    scope.row.validType == 1 &&
                                    scope.row.giftStyle !== 3 &&
                                    scope.row.giftStyle !== 5
                                "
                                style="
                                    width: 100px;
                                    text-align: right;
                                    text-align-last: right;
                                "
                                placeholder
                                :disabled="flag3"
                            ></el-input>
                            <el-date-picker
                                v-model="scope.row.validCreateDate"
                                v-if="
                                    scope.row.giftType === 2 &&
                                    scope.row.validType == 2 &&
                                    scope.row.giftStyle !== 3 &&
                                    scope.row.giftStyle !== 5
                                "
                                type="date"
                                value-format="yyyy-MM-dd"
                                style="width: 140px"
                                placeholder="请选择生效时间"
                                :disabled="flag3"
                            ></el-date-picker>
                            <el-date-picker
                                v-model="scope.row.validEndDate"
                                v-if="
                                    scope.row.giftType === 2 &&
                                    scope.row.validType == 2 &&
                                    scope.row.giftStyle !== 3 &&
                                    scope.row.giftStyle !== 5
                                "
                                type="date"
                                value-format="yyyy-MM-dd"
                                style="width: 140px"
                                placeholder="请选择失效时间"
                                :disabled="flag3"
                            ></el-date-picker>
                        </template>
                    </el-table-column> -->
          <el-table-column prop="prizeQuantity" label="赠品数量" width="100">
            <template slot-scope="scope">
              <el-input :maxlength="8" oninput="value=value.replace(/[^0-9]/g,'')" v-model="scope.row.prizeQuantity"
                :disabled="flag3"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="giftCount" label="赠送数量">
            <template slot-scope="scope">
              <el-input :maxlength="8" oninput="value=value.replace(/[^0-9]/g,'')" v-model="scope.row.giftCount"
                :disabled="flag3"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="surplusNum" label="剩余数量" min-width="100px">
            <template slot-scope="scope">
              {{ scope.row.winningQuantity != null || scope.row.winningQuantity != undefined ? scope.row.prizeQuantity
                - scope.row.winningQuantity : '/' }}
            </template>
          </el-table-column>
          <el-table-column prop="winningQuantityDay" label="当日中奖数量" min-width="110px"></el-table-column>
          <el-table-column prop="prizeQuantityDay" label="每日中奖上限" width="115">
            <template slot-scope="scope">
              <el-input :maxlength="8" oninput="value=value.replace(/[^0-9]/g,'')" v-model="scope.row.prizeQuantityDay"
                :disabled="flag3" v-on:input="compare(scope.row, scope.$index)"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="winningRate" label="中奖概率（%）" required width="120">
            <template slot-scope="scope">
              <el-input :maxlength="8" oninput="value=value.replace(/[^0-9.]/g,'')" v-model="scope.row.winningRate"
                @blur="blur($event, '中奖概率')" :disabled="flag3"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" width="200px" v-if="!this.flag3">
            <template slot-scope="scope">
              <el-button size="mini" @click="checkjiang(scope.row, scope.$index)" type="text">选择赠品</el-button>
              <el-button size="mini" @click="delprice(scope.$index)" type="text">删除奖项</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item>
            <el-button type="primary" @click="add()" size="mini" icon="el-icon-edit" v-if="!this.flag3">增加奖项</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div style="width: 100%; background: #fff; display: flex;flex-direction: column;justify-content: center;">
      <span style="font-size: 20px;margin: 30px 40px;display: inline-block; color: #000;">
        <i class="el-icon-document"></i>
        参与门店
      </span>

      <SelectStore :modelValue.sync="ruleForm" :storeList.sync="shopList" />
    </div>

    <div style="width: 100%; background: #fff; padding-bottom: 20px;">
      <span style="font-size: 20px;margin: 30px 40px;display: inline-block; color: #000;">
        <i class="el-icon-document"></i>
        活动商品
      </span>

      <el-form :model="ruleForm" label-width="150px" class="demo-ruleForm">
        <el-form-item label="活动商品：" required>
          <el-button v-if="!$route.params.flag3" type="primary" icon="el-icon-plus" @click="addGoods()"
            size="mini">添加商品</el-button>

          <el-table :data="goodsDTOS" style="width: 100%;"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }" border>
            <el-table-column label="商品编号" prop="goodsSeq"></el-table-column>
            <el-table-column label="商品名称" prop="goodsName"></el-table-column>
            <el-table-column label="商品分类" prop="goodsTypeName"></el-table-column>
            <el-table-column label="计量单位" prop="unitName"></el-table-column>
            <el-table-column label="商品价格(元)" prop="salePrice"></el-table-column>
            <el-table-column label="获得专项积分">
              <template slot-scope="scope">
                <el-input-number style="width: 100%" v-model="scope.row.score" :step="1" :min="0" size="mini" :disabled="$route.params.flag3" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" v-if="!$route.params.flag3">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="deleteGoods(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <div class="grid-content bg-purple">
            <el-form-item label="发布状态" prop="status">
              <el-select v-model="ruleForm.status" :disabled="$route.params.flag3" placeholder="请选择发布状态">
                <el-option label="发布" value="1"></el-option>
                <el-option label="不发布" value="0"></el-option>
              </el-select>
            </el-form-item>
          </div>
      </el-form>
    </div>

    <!-- <div
            style="
                background: #fff;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                color: #666;
            "
        >
            <div style="width: 100%">
                <span
                    style="
                        font-size: 20px;
                        margin: 30px 40px;
                        display: inline-block;
                        color: #000;
                    "
                >
                    <i class="el-icon-document"></i>
                    会员抽奖免费次数、中奖概率配置
                </span>
                <el-row :gutter="20">
                    <el-col :span="15" :push="1">
                        <div
                            class="grid-content bg-purple"
                            style="display: flex; margin: 10px 0"
                            v-for="(send, index) in options"
                            :key="index"
                        >
                            <div
                                style="
                                    display: flex;
                                    align-items: center;
                                    font-size: 14px;
                                "
                            >
                                <span>{{ send.gradelevelName }}</span>
                                <span>每天</span>
                                <span style="margin: 0 10px">
                                    <el-input
                                        v-model="data[index]"
                                        placeholder="请输入次数"
                                        oninput="value=value.replace(/[^0-9]/g,'')"
                                        :disabled="flag3"
                                    ></el-input>
                                </span>
                                <span>次,</span>
                            </div>
                            <div
                                style="
                                    display: flex;
                                    align-items: center;
                                    font-size: 14px;
                                "
                            >
                                <span style="margin: 0 10px"
                                    >对所有赠品中奖概率提升</span
                                >

                                <span style="margin: 0 10px">
                                    <el-input
                                        v-model="dataone[index]"
                                        placeholder="请输入提升概率"
                                        :disabled="flag3"
                                    ></el-input>
                                </span>
                                <span>%</span>
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </div> -->
    <el-button @click="postsure()" type="primary" style="margin-left: 700px"
      v-if="!$route.params.flag3" :loading="submitLoading">保存</el-button>
    <el-button @click="delsure()" type="primary" v-if="!$route.params.flag3">取消</el-button>
    <el-dialog title="赠品列表" :visible.sync="dialogVisible" width="80%">
      <!-- <el-form :inline="true" :model="giftForm">
        <el-form-item label="赠品类型：">
          <el-select v-model="giftForm.giftType" placeholder="请选择赠品类型" clearable>
            <el-option label="实物礼品" value="1"></el-option>
            <el-option label="虚拟礼品" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="赠品名称："><el-input v-model="giftForm.giftName" placeholder="请输入赠品名称" /></el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" icon="el-icon-search" @click="checkjiang(level)">搜索</el-button>
        </el-form-item>
      </el-form> -->
      <el-table :data="tableDataone" style="width: 100%" @select="handleRow" ref="tables"
        @selection-change="handleSelectionChange" border
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }" v-loading="giftLoading" height="400px">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
        <el-table-column prop="giftCode" label="赠品编码"></el-table-column>
        <el-table-column prop="giftName" label="赠品名称"></el-table-column>
        <el-table-column prop="giftPic" label="赠品图片">
          <template slot-scope="scope">
            <img :src="scope.row.giftPic" v-if="
              scope.row.giftPic != '' &&
              scope.row.giftPic != null
            " width="70" height="50" />
          </template>
        </el-table-column>
        <el-table-column prop="giftDesc" label="赠品描述"></el-table-column>
        <el-table-column prop="giftType" label="赠品类型">
          <template slot-scope="scope">
            <span v-if="scope.row.giftType === 1">实物赠品</span>
            <span v-if="scope.row.giftType === 2">虚拟赠品</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sure()">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- 选择赠品 -->
    <el-dialog title="选择商品" :visible.sync="dialogVisibleGoods" width="65%" @opened="getGoodsList(1)">
      <el-form :inline="true" :model="formGoods" class="search-form-inline">
        <el-form-item label="商品名称：">
          <el-input v-model="formGoods.goodsName" placeholder="请输入商品名称" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="商品分类：">
          <el-select v-model="formGoods.goodsType" placeholder="请选择商品分类">
            <el-option label="全部" value></el-option>
            <el-option v-for="item in goodsTypeList" :key="item.goodsTypeId" :label="item.goodsTypeName" :value="item.goodsTypeId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" icon="el-icon-search" @click="getGoodsList(1)">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="chooseGoodsList" tooltip-effect="dark" style="width: 100%"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }" border
        @selection-change="handleSelectionChange2" height="300" row-key="goodsId" ref="formGoodsRef">
        <el-table-column type="selection" width="55" :align="'center'" :selectable="selectableHandle" fixed></el-table-column>
        <el-table-column type="index" label="序号" width="60" :align="'center'"></el-table-column>
        <el-table-column prop="goodsSeq" label="商品编号" width="150" :align="'center'"></el-table-column>
        <el-table-column prop="goodsName" label="商品名称" :align="'center'"></el-table-column>
        <el-table-column prop="goodsTypeName" label="商品分类" :align="'center'"></el-table-column>
        <el-table-column prop="unitName" label="计量单位" width="100" :align="'center'"></el-table-column>
        <el-table-column prop="salePrice" label="商品价格(元)" width="100" :align="'center'"></el-table-column>
      </el-table>
      <div class="block" style="margin-top: 22px; overflow: hidden">
        <el-pagination @size-change="handleSizeChange2" @current-change="handleCurrentChange2"
          :page-sizes="[10, 20, 30, 50, 100, 150, 200]" :current-page="listQuery2.current" :page-size="listQuery2.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total2"></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleGoods = false">取 消</el-button>
        <el-button type="primary" @click="goodsConfirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
import { getmemberrule } from "@/api/membergrade";
import { queryStoreInfo, getWarzoneList } from "@/api/preSaleActivity";
import { getGoodsTypeList, querygoodsByName } from '@/api/product';
import { queryPrize, createActivityConfig } from "@/api/lotteryActivityset";
import { qryGiftBank } from "@/api/giftbank";
import imageUpload from "@/page/common/Image-upload";
import singleImageUpload from '@/page/common/single-image-upload'
import SelectStore from "@/components/form/SelectStore.vue";
export default {
  components: {
    imageUpload,
    singleImageUpload,
    SelectStore
  },
  data() {
    return {
      giftLoading: false,
      // keepAlive:true,
      data: [],
      dataone: [],
      options: [],

      ruleForm: {
        uuid: "",
        activityName: "",
        status: "0",
        date1: "",
        date2: "",
        activityRule: "",
        // activityScore: '',
        activityLimit: '',
        score: "",
        scoreName: "",
        cashDeadline: "",
        activityImg: '',
        isStore: '0'
      },

      submitLoading: false,
      formInline: {
        gradelevelName: "",
        gradelevelCode: ""
      },
      flag: false,
      flag3: false,
      selectone: [],
      dialogVisible: false,
      tableData: [],
      tableDataone: [],
      tableDatatwo: [],
      glevel: [],
      rules: {
        activityName: [
          { required: true, message: "请输入活动名称", trigger: "blur" }
        ],
        activityRule: [
          { required: true, message: "请输入活动规则", trigger: "blur" }
        ],
        // activityScore: [
        //   { required: true, message: "请输入获得抽奖资格金额", trigger: "blur" }
        // ],
        activityLimit: [
          { required: true, message: "请输入抽奖资格获得上限", trigger: "blur" }
        ],
        score: [
          { required: true, message: "请输入每日消耗积分", trigger: "blur" }
        ],
        scoreName: [
          { required: true, message: "请输入专项积分名称", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择发布状态", trigger: "blur" }
        ],

        activityImg: [
          { required: true, message: "请上传图片", trigger: "blur" }
        ],
        activityEntranceImg: [
          { required: true, message: "请上传图片", trigger: "blur" }
        ],
        cashDeadline: [
          { required: true, message: "请输入兑奖截止日期", trigger: "blur" }
        ],
        date1: [
          {
            type: "string",
            required: true,
            message: "请选择日期",
            trigger: "change"
          }
        ],
        date2: [
          {
            type: "string",
            required: true,
            message: "请选择时间",
            trigger: "change"
          }
        ]
      },

      // 选择门店
      shopList: [],
      dialogVisibleShop: false,
      formShop: {
        shopName: '',
        warzone: '',
      },
      lsShopList: [],
      lsCouponShopList: [],
      warzoneList: [],
      orgDTOS: [],
      listQuery: {
        current: 1,
        size: 10,
      },
      total: 0,

      // 选择商品
      goodsDTOS: [],
      dialogVisibleGoods: false,
      formGoods: {
        goodsType: '',
        goodsName: '',
      },
      goodsTypeList: [],
      chooseGoodsList: [],
      batchSelGoods: [],
      listQuery2: {
        current: 1,
        size: 10,
      },
      total2: 0,

      giftForm: {
        giftType: '',
        giftName: '',
      }
    };
  },
  mounted() {
    this._getmemberinfo();
    this.setprice();
    this.getWarzoneList();
    this.getGoodsTypeList();
    this.flag3 = this.$route.params.flag3;
    if (this.$route.params.edit) {
      this.flag = true;
      this.ruleForm.uuid = this.$route.params.edit.uuid;
      this.ruleForm.activityName = this.$route.params.edit.activityName;
      this.ruleForm.status = String(this.$route.params.edit.status);
      this.ruleForm.date1 = this.$route.params.edit.activityBeginTime;
      this.ruleForm.date2 = this.$route.params.edit.activityEndTime;
      this.ruleForm.activityRule = this.$route.params.edit.activityRule;
      this.ruleForm.activityImg = this.$route.params.edit.activityImg;
      // this.ruleForm.imgListone.push(this.$route.params.edit.activityImg)
      // this.ruleForm.activityScore = this.$route.params.edit.activityScore;

      this.ruleForm.activityLimit = this.$route.params.edit.activityLimit;
      this.ruleForm.activityEntranceImg = this.$route.params.edit.activityEntranceImg;

      this.ruleForm.cashDeadline = this.$route.params.edit.cashDeadline;
      this.ruleForm.score = this.$route.params.edit.score;
      this.ruleForm.scoreName = this.$route.params.edit.scoreName;
      this.tableData = this.$route.params.edit.promotionActivityPrizeConfigDTOList;
      // this.tableData.map(item => {
      //     if(item["uuid"] != undefined){
      //       delete item["uuid"];
      //     }
      //   });
      this.glevel = this.$route.params.edit.promotionActivityMemberConfigDTOList;
      this.ruleForm.isStore = this.$route.params.edit.isStore || '0';
      this.shopList = this.$route.params.edit.promotionActivityStoreDTOS;
      this.goodsDTOS = this.$route.params.edit.promotionActivityGoodsDTOS;
      console.log('~🚀🚀🚀🚀~🚀🚀🚀🚀~🚀🚀🚀🚀~ ~ this.$route.params.edit:', this.$route.params.edit);
    } else {
      this.flag = false;
    }
  },
  methods: {
    numberBlur(e, name) {
      if (e.target.value == "") {
        return;
      }
      let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      if (!flag) {
        this.$message({
          message: name + "请输入正整数",
          type: "warning"
        });
        e.target.value = "";
      }
    },
    enterinput(v, index) {
      console.log(this.data, "88");
      console.log(this.dataone, "88999");
      console.log(v, index, "opo9");
    },
    enterinputone(v, index) {
      console.log(v, index, "opo9");
    },
    goback() {
      this.$router.go("-1");
    },
    handleRow(selection, row) {
      // 先清除所有选中的
      this.$refs.tables.clearSelection();
      // 当前的点击实现勾选
      this.$refs.tables.toggleRowSelection(row);
    },

    _getmemberinfo() {
      let data = {
        size: 10,
        current: 1,
        condition: {
          activityType: 2
        },
        ascs: [],
        descs: []
      };
      getmemberrule(data).then(res => {
        this.options = res.records;
        if (this.$route.params.edit) {
          this.glevel.forEach((item, i) => {
            let index = this.options.findIndex((ff, i) => { return ff.uuid === item.memberLevelId });
            this.data[index] = item.dayTimes;
            this.dataone[index] = item.addWinningRate;
          }
          );
        } else {
          this.options.forEach((item, i) => {
            this.data.push("0");
            this.dataone.push("0");
          });
        }
      });
    },
    setprice() {
      this.tableData.push(
        { prizeLevel: "1", prizeLevelName: "一等奖", giftCode: "" },
        { prizeLevel: "2", prizeLevelName: "二等奖", giftCode: "" },
        { prizeLevel: "3", prizeLevelName: "三等奖", giftCode: "" },
        { prizeLevel: "4", prizeLevelName: "四等奖", giftCode: "" },
        { prizeLevel: "5", prizeLevelName: "五等奖", giftCode: "" }
      );
    },

    checkjiang(v, index) {
      this.level = index;
      this.dialogVisible = true;
      let data = {
        size: 99,
        current: 1,
        condition: {
          // giftName: "",
          giftCode: "",
          ActivityType: 4,
          ...this.giftForm
          // giftType: 2,
          // ActivityType: 2
        },
        ascs: [],
        descs: []
      };
      this.giftLoading = true;
      qryGiftBank(data)
        .then(res => {
          res.records.forEach((item, i) => {
            item.validType = item.giftType == 1 ? "2" : "1";
            // this.$set(item,'validType',item.giftType == 1 ? "2" : "1");
          });
          this.tableDataone = res.records;
          if (this.tableDataone.length > 0) {
            for (var i in this.tableData) {
              if (this.tableData[i].giftCode != null && this.tableData[i].giftCode != '' && this.tableData[i].giftCode.length != 0) {
                this.removeByValue(this.tableDataone, "giftCode", this.tableData[i].giftCode);
              }
            }
          }
        }).finally(() => {
          this.giftLoading = false
        })
      // .then(() => {
      // for (let i = 0; i < this.tableDataone.length; i++) {
      // if (this.tableDataone[i].giftCode == v.giftCode) {
      //   this.$refs.tables.toggleRowSelection(this.tableDataone[i], true);
      // }
      // }
      // }
    },
    checkboxT(row, rowIndex) {
      // if(rowIndex==4){
      if (true) {
        //  if(row.giftCode =='1'){
        return false;//禁用
      } else {
        return true;//不禁用
      }
    },
    blur(e, name) {
      if (e.target.value > 100) {
        this.$message({
          message: name + "请正确输入中奖概率且不大于100",
          type: "warning"
        });
        return e.target.value = '';
      }
      // let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      let a = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
      let flag = a.test(e.target.value);
      if (!flag) {
        this.$message({
          message: name + "请正确输入中奖概率且不大于100",
          type: "warning"
        });
        e.target.value = '';
      }
    },
    sure() {
      this.dialogVisible = !this.dialogVisible;
      this.tableData.forEach((item, i) => {
        if (this.level == i) {
          this.selectData[0].prizeLevelName = this.tableData[i].prizeLevelName;
          this.selectData[0].prizeLevel = this.tableData[i].prizeLevel;
          this.selectData[0]["prizeId"] = this.selectData[0]["uuid"];
          delete this.selectData[0]["uuid"];
          let returnedTarget = Object.assign({}, this.tableData[i], this.selectData[0]);
          this.$set(returnedTarget, 'prizeQuantity', 1)
          this.$set(returnedTarget, 'giftCount', 1)
          this.$set(returnedTarget, 'prizeQuantityDay', 1)
          this.$set(returnedTarget, 'winningRate', '')
          if (this.selectData[0].giftType == 2) {
            this.$set(returnedTarget, 'deliveryType', '1')
          }
          this.tableData[i] = returnedTarget;
          this.tableDatatwo = this.tableData;
        }
      });
      this.tableData = [];
      this.tableDatatwo.forEach((item, i) => {
        this.tableData.push(item);
      });
    },
    handleSelectionChange(val) {
      this.selectData = val;
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    add() {
      this.tableData.push({ prizeLevel: this.tableData.length + 1 + "" });
    },
    delprice(index) {
      this.tableData.splice(index, 1);
    },
    postsure() {
      if (this.ruleForm.activityName == "" || this.ruleForm.activityName == null) {
        this.$message.error("请输入活动名称");
        return;
      }
      if (this.ruleForm.date1 == "" || this.ruleForm.date1 == null) {
        this.$message.error("请输入开始日期");
        return;
      }
      if (this.ruleForm.date2 == "" || this.ruleForm.date2 == null) {
        this.$message.error("请输入结束日期");
        return;
      }
      if (this.ruleForm.cashDeadline == "" || this.ruleForm.cashDeadline == null) {
        this.$message.error("请输入兑奖截止日期");
        return;
      }
      if (this.ruleForm.date1 > this.ruleForm.date2) {
        this.$message.error("结束时间不能早于开始时间");
        return;
      }
      if (this.ruleForm.cashDeadline < this.ruleForm.date1) {
        this.$message.error("兑奖截止日期不能早于开始时间");
        return;
      }
      if (this.ruleForm.activityImg == "" || this.ruleForm.activityImg == null) {
        this.$message.error("请上传活动背景图");
        return;
      }

      if (this.ruleForm.activityEntranceImg == "" || this.ruleForm.activityEntranceImg == null) {
        this.$message.error("请上传专卖店活动入口图片");
        return;
      }

      if (this.ruleForm.activityRule == "" || this.ruleForm.activityRule == null) {
        this.$message.error("请输入活动规则");
        return;
      }

      // if (this.ruleForm.activityScore == "" || this.ruleForm.activityScore == null) {
      //   this.$message.error("请输入获得抽奖资格金额");
      //   return;
      // }

      if (this.ruleForm.activityLimit === "" || this.ruleForm.activityLimit == null) {
        this.$message.error("请输入抽奖资格获得上限");
        return;
      }

      if (this.ruleForm.score == "" || this.ruleForm.score == null) {
        this.$message.error("请输入每日消耗积分");
        return;
      }

      if (this.ruleForm.scoreName == "" || this.ruleForm.scoreName == null) {
        this.$message.error("请输入专项积分名称");
        return;
      }

      this.options.forEach((item, i) => {
        if (this.$route.params.edit) {
          this.glevel.forEach((item, i) => {
            let index = this.options.findIndex((ff, i) => { return ff.uuid === item.memberLevelId });
            this.glevel[i].dayTimes = this.data[index];
            this.glevel[i].addWinningRate = this.dataone[index];
          });
        } else {
          this.glevel.push({
            uuid: "",
            memberLevelId: this.options[i].uuid,
            activityId: "",
            dayTimes: this.data[i],
            addWinningRate: this.dataone[i],
            status: 1
          });
        }
      });
      this.selectone = [];
      this.tableData.forEach((item, i) => {
        item.prizeLevel = i + 1;
        if (this.tableData[i].giftCode) {
          this.selectone.push(this.tableData[i]);
        }
      });
      let r = new RegExp("^[1-9][0-9]*$");
      for (var i in this.selectone) {
        var flag1 = true;
        var flag2 = true;
        var flag3 = true;
        var prizeQuantity = this.selectone[i].prizeQuantity;
        var prizeQuantityDay = this.selectone[i].prizeQuantityDay;
        var winningRate = this.selectone[i].winningRate;
        if (prizeQuantity == null || prizeQuantity == "" || !r.test(prizeQuantity)) {
          flag1 = false;
          break;
        }
        if (prizeQuantityDay == null || prizeQuantityDay == "" || !r.test(prizeQuantityDay)) {
          flag2 = false;
          break;
        }
        if (prizeQuantityDay == null || prizeQuantityDay == "" || !r.test(prizeQuantityDay)) {
          flag2 = false;
          break;
        }
        if (winningRate == null || winningRate === "") {
          flag3 = false;
          break;
        }
      }
      if (!flag1) {
        this.$message({ message: "请正确输入赠品数量", type: "warning" }); return;
      }
      if (!flag2) {
        this.$message({ message: "请正确输入每日中奖上限", type: "warning" }); return;
      }
      if (!flag3) {
        this.$message({ message: "请正确输入中奖概率", type: "warning" }); return;
      }
      if (false) {
        let newData = [];
        let obj = {};
        this.selectone.map(item => {
          obj = item;
          if (item["uuid"] != undefined) {
            // obj["prizeId"] = item["uuid"];
            // delete obj["uuid"];
            newData.push(obj);
          }
        });
      }

      if (this.ruleForm.isStore == "" || this.ruleForm.isStore == null) {
        this.$message.error("请选择门店范围");
        return;
      }

      if (this.goodsDTOS.length <= 0) {
        this.$message.error("请添加商品");
        return;
      }

      if (this.ruleForm.isStore == '1' && this.shopList.length <= 0) {
        this.$message.error("请添加适用门店");
        return;
      }

      if (this.goodsDTOS.length > 0) {
        let tips = '';
        const verifygoods = this.goodsDTOS.some((item, index) => {
          console.log('~🚀🚀🚀🚀~🚀🚀🚀🚀~🚀🚀🚀🚀~ ~ item:', item);
          if (item.score == null || item.score === "") {
            tips = `第${index + 1}个商品专项积分不可为空`;
            return true
          } else {
            return false
          }
        })
        if (verifygoods) {
          this.$message.error(tips ? tips : '请添加商品专项积分');
          return;
        }
      }

      let data = {
        uuid: this.ruleForm.uuid,
        activityType: 4,
        activityName: this.ruleForm.activityName,
        activityBeginTime: this.ruleForm.date1,
        activityEndTime: this.ruleForm.date2,
        cashDeadline: this.ruleForm.cashDeadline,
        score: this.ruleForm.score,
        status: this.ruleForm.status,
        activityRule: this.ruleForm.activityRule,
        activityImg: this.ruleForm.activityImg,
        // activityScore: this.ruleForm.activityScore,
        activityEntranceImg: this.ruleForm.activityEntranceImg,
        score: this.ruleForm.score,
        scoreName: this.ruleForm.scoreName,
        activityLimit: this.ruleForm.activityLimit,
        promotionActivityPrizeConfigDTOList: this.selectone,
        promotionActivityMemberConfigDTOList: this.glevel,
        isStore: this.ruleForm.isStore,
        promotionActivityStoreDTOS: this.ruleForm.isStore == '1' ? this.shopList.map(item => {
          return { orgSeq: item.orgSeq }
        }) : [],
        promotionActivityGoodsDTOS: this.goodsDTOS.map(item => {
          return {
            goodsId: item.goodsId || item.uuid,
            score: item.score
          }
        })
      };

      // const validResult = this.hasEmptyFields(data.promotionActivityPrizeConfigDTOList);

      // if (validResult) {
      //   this.$message.error(typeof validResult === 'string' ? validResult : '填写的奖品信息有误,请检查');
      //   return
      // }

      // this.keepAlive = false;
      console.log(data);
      if (this.$route.params.edit) {
        this.submitLoading = true;
        createActivityConfig(data).then(res => {
          this.tableDataone = res.records;
          if (res.code == "1") {
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success"
            });
            this.glevel = [];
            // this.$router.push("lotteryActivityxinset");
            this.$router.back();
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: "error"
            });
            this.selectone = [];
          }
        }).finally(() => {
          this.submitLoading = false
        });
      } else {
        this.submitLoading = true;
        createActivityConfig(data).then(res => {
          this.tableDataone = res.records;
          if (res.code == "1") {
            this.$message({
              showClose: true,
              message: "保存成功",
              type: "success"
            });
            this.glevel = [];
            // this.$router.push("lotteryActivityxinset");
            this.$router.back();
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: "error"
            });
            this.selectone = [];
          }
        }).finally(() => {
          this.submitLoading = false
        });
      }
    },

    // 对数组中相应的字段进行验证
    hasEmptyFields(array, fields) {
      fields = [
        'giftPic', 'giftName', 'cashCouponMoney', 'prizeQuantity', 'cashCouponLimit', 'giftCount', 'prizeQuantityDay', 'winningRate'
      ];
      const greaterThanZero = [
        'prizeQuantity', 'cashCouponLimit', 'giftCount', 'prizeQuantityDay', 'winningRate'
      ];

      // 边界判断
      if (!Array.isArray(array)) return false;
      if (!Array.isArray(fields)) return false;

      // 边界判断
      if (!Array.isArray(array) || array.length === 0) {
        return false; // 没有数据，视为无错误
      }

      // 使用 for...of，可以中途 return 错误信息
      for (let i = 0; i < array.length; i++) {
        const item = array[i];

        // 确保是对象
        if (typeof item !== 'object' || item === null) {
          return `第 ${i + 1} 项数据格式错误，必须是对象`;
        }

        // 1. 检查必填字段是否为空
        for (const field of fields) {
          const value = item[field];

          if (greaterThanZero.includes(field)) {
            if (value == null || value === '' || value <= 0) {
              return `${this.changePrizeLevel(i)} 填写的奖品信息有误,请检查`;
            }
          } else {
            if (value == null || value === '') {
              return `${this.changePrizeLevel(i)} 填写的奖品信息有误,请检查`;
            }
          }
        }

        // 2. 业务逻辑校验：单次赠送数量不能大于总奖品数量
        if (item.prizeQuantity < item.giftCount) {
          return `${this.changePrizeLevel(i)} 的单次赠送数量不能大于奖品数量`;
        }
      }

      // 全部通过
      return false;
    },

    // 几等奖的数字转换文字
    changePrizeLevel(index) {
      // const numMap = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
      return `赠品配置第${index + 1}项`;
    },

    delsure() {
      // this.$router.push("lotteryActivityxinset");
      this.$router.back();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    compare(value, index) {
      var number = value.prizeQuantity;
      var val = value.prizeQuantityDay;
      if (number === null || number === undefined || number === "") {
        this.$message({ showClose: true, message: "请输入赠品数", type: "info" });
        this.tableData[index].prizeQuantityDay = ''
        return false;
      }
      if (val === null || val === undefined || val === "") {
        this.$message({ showClose: true, message: "请输入每日中奖数", type: "info" });
        this.tableData[index].prizeQuantityDay = ''
        return false;
      } else {
        if (Number(val) > Number(number)) {
          this.$message({ showClose: true, message: "每日中奖数不能高于赠品数", type: "info" });
          this.tableData[index].prizeQuantityDay = number
          return false;
        }
      }
    },
    compare2(e, name, val) {
      if (e.target.value == "") {
        return;
      }
      let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      if (!flag) {
        this.$message({
          message: name + "请输入正整数",
          type: "warning"
        });
        e.target.value = "";
      }
      if (val === null || val === undefined || val === "") {
        this.$message({ showClose: true, message: "请输入每日中奖数", type: "info" });
        return e.target.value = "";
      } else {
        if (Number(e.target.value) > Number(val)) {
          this.$message({ showClose: true, message: "每日中奖数不能高于赠品数", type: "info" });
          return e.target.value = val;
        }
      }
    },
    // 数组，属性，属性值
    removeByValue: function (arr, attr, value) {
      if (arr == null) {
        return;
      }
      var index = 0;
      for (var i in arr) {
        if (arr[i][attr] == value) {
          index = i;
          break;
        }
      }
      arr.splice(index, 1);
    },
    todataformat(val, type) {

      // 值，符号
      if (val === null || val === undefined || val === "") {
        return "";
      } else {
        if (this.ruleForm.date1 == "" || this.ruleForm.date1 == null) {
          this.$message.error("请输入开始时间");
          return "";
        }
        if (this.ruleForm.date2 == "" || this.ruleForm.date2 == null) {
          this.$message.error("请输入结束时间");
          return "";
        }
        if (val < this.ruleForm.date1) {
          this.$message.error("兑奖截止日期不能早于开始时间");
          return "";
        }
        return val;
      }
    },

    couponShopChecked(row) {
      this.lsCouponShopList = row;
    },
    // 查询区域
    getWarzoneList() {
      const data = {};
      getWarzoneList(data).then((res) => {
        this.warzoneList = res.records;
      });
    },
    // 查询门店接口
    getShopList(current) {
      let data = {
        size: this.listQuery.size,
        current: current,
        condition: {
          upOrgSeq: this.formShop.warzone,
          storeName: this.formShop.shopName,
        },
        ascs: [],
        descs: [],
      };
      queryStoreInfo(data).then((res) => {
        this.orgDTOS = res.records;
        let arrayList = res.records;
        this.total = res.total;
        // // 去掉已选的
        // this.shopList.forEach(item=>{
        //   arrayList.forEach((orgItem,orgIndex)=>{
        //     if(item.uuid===orgItem.uuid){
        //       console.log("找到了")
        //       this.orgDTOS.splice(orgIndex,1);
        //     }
        //   })
        // })
        console.log('shopList', this.shopList);

        for (var i in this.shopList) {
          this.removeByValue(this.orgDTOS, 'uuid', this.shopList[i].orgSeq);
          this.total -= 1;
          this.total = this.total < 0 ? 0 : this.total;
        }
      });
      // }
      this.loading = false;
    },
    handleSizeChange3(val) {
      this.listQuery.size = val;
      this.getShopList(1);
    },
    handleCurrentChange3(val) {
      this.listQuery.current = val;
      this.getShopList(val);
    },
    shopChecked(row) {
      this.lsShopList = row;
    },

    // 选择门店
    selectShop() {
      this.formShop.warzone = "";
      this.formShop.shopName = "";
      // 显示选择门店对话框
      this.dialogVisibleShop = !this.dialogVisibleShop;
    },
    deleteShop() {
      // 删除已选择的门店
      this.orgDTOS = this.orgDTOS.concat(this.lsCouponShopList);
      for (var i in this.lsCouponShopList) {
        this.removeByValue(
          this.shopList,
          'uuid',
          this.lsCouponShopList[i].uuid
        );
      }
    },
    shopConfirm() {
      this.dialogVisibleShop = !this.dialogVisibleShop;
      this.shopList = this.shopList.concat(this.lsShopList);
      for (var i in this.lsShopList) {
        this.removeByValue(this.orgDTOS, 'uuid', this.lsShopList[i].uuid);
      }
    },

    // 选择商品
    getGoodsTypeList() {
      getGoodsTypeList().then((res) => {
        this.goodsTypeList = res.records;
      });
    },
    addGoods() {
      this.dialogVisibleGoods = !this.dialogVisibleGoods;
    },
    getGoodsList(current) {
      this.listQuery2.current = current;
      let data = {
        size: this.listQuery2.size,
        current: this.listQuery2.current,
        condition: {
          goodsName: this.formGoods.goodsName,
          goodsTypeId: this.formGoods.goodsType,
          // status: 0,
        },
        ascs: [],
        descs: [],
      };
      querygoodsByName(data).then((res) => {
        this.chooseGoodsList = res.records;
        this.total2 = res.total;

        // this.$nextTick(() => {
        //   this.goodsDTOS.forEach((item) => {
        //     const curItem = res.records.find((i) => i.goodsId == item.goodsId);
        //     if (this.$refs.formGoodsRef && this.$refs.formGoodsRef.toggleRowSelection && curItem) {
        //       this.$refs.formGoodsRef.toggleRowSelection(curItem, true);
        //     }
        //   })
        // })
      })
    },
    goodsConfirm() {
      this.dialogVisibleGoods = !this.dialogVisibleGoods;
      this.goodsDTOS = this.goodsDTOS.concat(this.batchSelGoods);
    },
    handleSelectionChange2(val) {
      this.batchSelGoods = val;
    },
    handleCurrentChange2(val) {
      this.listQuery2.current = val;
      this.getGoodsList(val);
    },
    handleSizeChange2(val) {
      this.listQuery2.size = val;
      this.getGoodsList(1);
    },
    deleteGoods(index, row) {
      this.goodsDTOS.splice(index, 1);
    },

    selectableHandle(row) {
      const res = this.goodsDTOS.some(item => (item.goodsId == row.uuid || item.uuid == row.uuid))
      return !res
    }
  },
  // beforeRouteLeave(to, from, next) {
  //   // 设置下一个路由的 meta
  //   to.meta.keepAlive = this.keepAlive; // C 跳转到 A 时让 A 不缓存，即刷新
  //   next();
  // },
};
</script>
